<script setup lang="ts">
import { handleQueryImg } from "@/api/queryImg";
import axios from "axios";
import { ElLoading } from "element-plus";
import { nextTick, onBeforeMount, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import svgPanZoom from "svg-pan-zoom";

const svgRef = ref<any>(null);
const route = useRoute();
const Svgdata = ref();
// 展示svg图片
const showSvg = ref();
// 色块
const ColorLumps = ref();
// 所选中的色块
const selectedColor = ref<number | null>(null);
// 是否显示边框
const checked1 = ref(true);
// 是否显示标签
const checked2 = ref(true);
const sanitizeSvg = (svgData: string) => {
  // 创建一个 DOMParser 实例
  const parser = new DOMParser();
  // 解析 SVG 数据
  const doc = parser.parseFromString(svgData, "image/svg+xml");
  // 获取 SVG 元素
  const svg = doc.querySelector("svg");

  if (svg) {
    // 获取原始宽度和高度
    const width = svg.getAttribute("width") || "100";
    const height = svg.getAttribute("height") || "100";
    // 移除宽度和高度属性
    svg.removeAttribute("width");
    svg.removeAttribute("height");
    // 确保存在 viewBox 属性
    if (!svg.hasAttribute("viewBox")) {
      svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
    }
  }

  // 返回修改后的 SVG 数据
  return new XMLSerializer().serializeToString(doc);
};

const updateSvgColors = (index: number) => {
  const loading = ElLoading.service({
    lock: true,
    text: "重新加载中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const parser = new DOMParser();
  const doc = parser.parseFromString(showSvg.value!, "image/svg+xml");
  const svg = doc.querySelector("svg");

  if (svg) {
    const paths = svg.querySelectorAll("path");

    // 处理每个路径
    paths.forEach((path) => {
      // 获取当前路径的样式
      const style = path.getAttribute("style");
      // 尝试根据路径的属性找到该路径是否属于当前色块（通过index或者其他条件）
      const isSelectedPath =
        path.getAttribute("data-index") === index.toString(); //  data-index 属性

      if (isSelectedPath) {
        if (style) {
          const newStyle = style.replace(
            /fill:\s*[^;]+/,
            `fill: rgb(${ColorLumps.value[index][0]}, ${ColorLumps.value[index][1]}, ${ColorLumps.value[index][2]})`
          );
          // 如果是选中的路径，保持原色或者设置选中颜色
          path.setAttribute("style", newStyle);
        } else {
          path.setAttribute(
            "style",
            `fill: rgb(${ColorLumps.value[index][0]}, ${ColorLumps.value[index][1]}, ${ColorLumps.value[index][2]})`
          );
        }
      } else {
        // 如果是非选中的路径，设置为白色
        if (style) {
          const newStyle = style.replace(/fill:\s*[^;]+/, "fill: white");
          path.setAttribute("style", newStyle);
        } else {
          path.setAttribute("style", "fill: white");
        }
      }
    });
  }
  // 更新显示的SVG
  showSvg.value = new XMLSerializer().serializeToString(doc);
  updateBorder(checked1.value);
  updateLabel(checked2.value);
  setTimeout(() => {
    loading.close();
  }, 2000);
};

// 点击色块
const handleColorClick = (color: number[], index: number) => {
  if (selectedColor.value === index) {
    selectedColor.value = null;
    showSvg.value = Svgdata.value;
    updateBorder(checked1.value);
    updateLabel(checked2.value);
    return;
  }
  selectedColor.value = index;
  updateSvgColors(index);
};

// 更新边框
const updateBorder = (key: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: "重新加载中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const parser = new DOMParser();
  const doc = parser.parseFromString(showSvg.value!, "image/svg+xml");
  const svg = doc.querySelector("svg");
  if (key) {
    // 如果要恢复边框
    if (svg) {
      const paths = svg.querySelectorAll("path");
      paths.forEach((path) => {
        // 获取当前路径的样式
        const style = path.getAttribute("style");
        if (style) {
          // 替换 stroke 和 stroke-width 样式，设置为与填充颜色一致
          const newStyle = style
            .replace(/stroke:\s*[^;]+/, `stroke: rgb(179, 179, 179) `)
            .replace(/stroke-width:\s*[^;]+/, `stroke-width: 1 `); // 你可以自定义边框宽度

          path.setAttribute("style", newStyle);
        } else {
          // 如果没有样式，直接设置填充颜色和边框颜色一致
          path.setAttribute(
            "style",
            `stroke: rgb(179, 179, 179) ; stroke-width: 1 `
          );
        }
      });
    }
  } else {
    if (svg) {
      const paths = svg.querySelectorAll("path");
      paths.forEach((path) => {
        const style = path.getAttribute("style");
        let fillColor = "none";

        // 1. 从 style 属性中提取 fill 颜色
        const fillMatch = style?.match(/fill:\s*([^;]+)/);
        if (fillMatch) {
          fillColor = fillMatch[1].trim();
        } else {
          // 2. 若 style 无 fill，尝试从独立属性获取
          fillColor = path.getAttribute("fill") || "none";
        }
        // 清除边框
        if (style) {
          const newStyle = style
            .replace(/stroke:\s*[^;]+/, `stroke:  ${fillColor} `)
            .replace(/stroke-width:\s*[^;]+/, "stroke-width:1px ");

          path.setAttribute("style", newStyle);
        } else {
          path.setAttribute("style", `stroke: ${fillColor} ; stroke-width: 0 `);
        }
      });
    }
  }
  // 更新显示的SVG
  showSvg.value = new XMLSerializer().serializeToString(doc);
  setTimeout(() => {
    loading.close();
  }, 2000);
};

// 更新标签
const updateLabel = (key: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: "重新加载中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const parser = new DOMParser();
  const doc = parser.parseFromString(showSvg.value!, "image/svg+xml");
  const svg = doc.querySelector("svg");
  if (svg) {
    const texts = svg.querySelectorAll("text");
    texts.forEach((text: any) => {
      if (key) {
        text.setAttribute("fill", "#b3b3b3");
      } else {
        const FontColor = text.getAttribute("font-color");
        if (FontColor) {
          text.setAttribute("fill", FontColor);
        }
        if (selectedColor.value) {
          text.setAttribute("fill", "white");
        }
      }
    });
  }
  showSvg.value = new XMLSerializer().serializeToString(doc);
  setTimeout(() => {
    loading.close();
  }, 2000);
};

onBeforeMount(() => {
  if (route.query.id) {
    handleQueryImg(route.query.id)
      .then(async (res) => {
        Svgdata.value = sanitizeSvg(res.data.svg_data);
        showSvg.value = await Svgdata.value;
        ColorLumps.value = res.data.colors_by_index;
      })
      .catch((err) => {
        console.log(err);
      });
  }
});
onMounted(() => {});

// 大图弹窗
const DialogSvg = ref(false);

// 点击 SVG 后放大显示
const handleSvgClick = () => {
  DialogSvg.value = true;
};
// 关闭弹窗
const handleClose = () => {
  DialogSvg.value = false;
};
const panZoomInstance = ref<any>(null);
// 在 watch 中初始化
watch(DialogSvg, async (newVal) => {
  if (newVal) {
    await nextTick();
    const svgElement = document.querySelector(".svg-content svg");
    if (svgElement) {
      panZoomInstance.value = svgPanZoom(svgElement as SVGElement, {
        zoomEnabled: true,
        controlIconsEnabled: true,
        fit: true,
        center: true,
        minZoom: 0.1,
        maxZoom: 10,
        zoomScaleSensitivity: 0.5,
      });
    }
  } else {
    // 当弹窗关闭时，销毁实例
    if (panZoomInstance.value) {
      panZoomInstance.value.destroy();
      panZoomInstance.value = null;
    }
  }
});
</script>

<template>
  <div class="home" v-if="Svgdata && route.query.id">
    <div
      v-if="showSvg"
      ref="svgRef"
      class="svg-container"
      v-html="showSvg"
      @click="handleSvgClick"
    ></div>
    <div class="tool">
      <div class="color-lumps">
        <div
          v-for="(color, index) in ColorLumps"
          :key="index"
          :style="`background-color:rgb(${color[0]}, ${color[1]}, ${color[2]})`"
          :class="['color-lump', selectedColor === index ? 'selected' : '']"
          @click="handleColorClick(color, index)"
        >
          <span>{{ index }}</span>
        </div>
      </div>
      <div class="checkbox_container">
        <el-checkbox v-model="checked1" size="large" @change="updateBorder">
          <span>显示边框</span>
        </el-checkbox>
        <el-checkbox v-model="checked2" size="large" @change="updateLabel">
          <span>显示标签</span>
        </el-checkbox>
      </div>
    </div>
    <div class="mask-layer" v-if="showSvg && DialogSvg">
      <div class="svg-zoom-container">
        <div class="close-btn" @click="handleClose">×</div>
        <div class="svg-content" v-html="showSvg"></div>
      </div>
    </div>
  </div>
  <div class="home empty-home" v-else>
    <el-empty description="请联系客服获取完整网站地址链接" />
  </div>
</template>
<style>
.svg-container svg {
  width: 100% !important;
  height: auto !important;
}
</style>
<style lang="scss">
#svg_content {
  width: 100%;
  height: 100%;
}
.svg-zoom-container {
  width: 90%;
  height: 90%;
  background: white;
  padding: 20px;
  border-radius: 8px;
  .close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background: rgba(0, 0, 0, 0.1);
    color: #fff;
    border-radius: 50%;
    cursor: pointer;
    font-size: 20px;

    &:hover {
      background: rgba(0, 0, 0, 0.2);
    }
  }
  .svg-content {
    width: 100%;
    height: 100%;

    svg {
      width: 100%;
      height: 100%;
    }
  }
}
.home {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
.empty-home {
  display: flex;
  align-items: center;
  justify-content: center;
  .el-empty {
    height: 100%;
  }
}

.svg-container {
  // flex: 1;
  width: 100%;
  cursor: pointer;
}
.svg-container svg {
  width: 100% !important;
  height: auto !important;
}

.tool {
  overflow: auto;
}

.color-lumps {
  // flex: 1;
  overflow-y: auto;
  margin-top: 20px;

  .color-lump {
    padding: 10px;
    text-align: center;
    text-shadow: #fff 0px 0px 5px;
    cursor: pointer;
    border-radius: 5px;
    border: 2px;
  }
  .selected {
    border: 2px solid #72fac1;
  }
}
.checkbox_container {
  display: flex;
  flex-direction: column;
}
.mask-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.panZoom_box {
  width: 100%;
  height: 100%;
  // display: flex;
  // justify-content: center;
  // align-items: center;
}
</style>
<style lang="scss">
@import url("../assets/style/home.scss");
</style>
